import {onMounted, onUnmounted, ref, computed} from "vue";
import { filter } from "../util/todoStorage";

const validhash = ["all,", "active", "completed"];
export default function (todosRef) {
    const visibiltyRef = ref("all");

    const onHashChange = () => {
        const hash = location.hash.replace(/#\/?/, "");
        if(validhash.includes(hash)) {
            //有效的
            visibiltyRef.value = hash;
        } else {
            location.hash = "";
            visibiltyRef.value = "all";
        }
    }
    onHashChange();
    //1. 组件挂载完成的生命周期函数
    onMounted(() => {
        window.addEventListener("hashchange", onHashChange);
    })

    //2. 组件销毁过后的生命周期函数
    onUnmounted(() => {
        window.removeEventListener("hashchange", onHashChange);
    });

    const filteredTodosRef = computed(() => {
        return filter(todosRef.value, visibiltyRef.value);
    })

    const remainingRef = computed(() => {
        return filter(todosRef.value, "active").length;
    })

    const completedRef = computed(() => {
        return filter(todosRef.value, "completed").length;
    })

    return {
        visibiltyRef,
        filteredTodosRef,
        remainingRef,
        completedRef,
    }
}